# -*- coding: utf-8 -*-

# 根据系统内置命令去获取MAC

import os
import platform
import re
import random
import struct

class IP2MAC:
    def __init__(self):
        self.patt_mac = re.compile('([a-f0-9]{2}[-:]){5}[a-f0-9]{2}', re.I)
        self.gen_mac()

    def gen_mac(self):
        mac_bin_list = []
        mac_hex_list = []
        for i in range(1, 7):
            i = random.randint(0x00, 0xff)
            mac_bin_list.append(i)
        Fake_HW = struct.pack("BBBBBB", mac_bin_list[0], mac_bin_list[1], mac_bin_list[2], mac_bin_list[3],
                              mac_bin_list[4], mac_bin_list[5])
        for j in mac_bin_list:
            mac_hex_list.append(hex(j))
        self.Hardware = ":".join(mac_hex_list).replace("0x", "")
        return self.Hardware


    def getMac(self, ip):
        sysstr = platform.system()
        if sysstr == 'Windows':
            macaddr = self.__forWin(ip)
        elif sysstr == 'Linux':
            macaddr = self.__forLinux(ip)
        else:
            macaddr = None
        return macaddr or self.Hardware

    def __forWin(self, ip):
        os.popen('ping -n 1 -w 500 {} > nul'.format(ip))
        macaddr = os.popen('arp -a {}'.format(ip))
        macaddr = self.patt_mac.search(macaddr.read())
        if macaddr:
            macaddr = macaddr.group()
        else:
            macaddr =  self.Hardware
        return macaddr

    def __forLinux(self, ip):
        os.popen('ping -nq -c 1 -W 500 {} > /dev/null'.format(ip))
        result = os.popen('arp -an {}'.format(ip))
        result = self.patt_mac.search(result.read())
        return result.group() if result else self.Hardware


if __name__ == '__main__':
    g = IP2MAC()
    print(g.getMac('132.155.23.12'), g.gen_mac(), '\n')